package pers.w.chaptertalk.ui.login;

import android.os.Handler;
import android.os.Message;
import android.util.Patterns;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.Fun;

public class LoginViewModel extends ViewModel  {

    private MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>();
    private MutableLiveData<String> loginResult = new MutableLiveData<>();



    LiveData<LoginFormState> getLoginFormState() {
        return loginFormState;
    }

    LiveData<String> getLoginResult() {
        return loginResult;
    }

    void login(String url, String username, String password) {
        // can be launched in a separate asynchronous job
        new Thread(()->{
            Connection conn = Jsoup.connect(url);
            conn.data("u",username);
            conn.data("p",password);
            conn.data("e", Fun.webEncrypted(username,password));
            Message msg = loginHandler.obtainMessage();

            Document doc;
            try {
                doc = conn.post();
                msg.obj = doc.text();
            } catch (IOException e) {
               // e.printStackTrace();
                msg.obj = "无法连接";
            }
            loginHandler.sendMessage(msg);

        }).start();

    }

    private Handler loginHandler = new Handler(msg -> {
        loginResult.setValue((String) msg.obj);
        return false;
    });
    void loginDataChanged(String username, String password) {
        if (!isUserNameValid(username)) {
            loginFormState.setValue(new LoginFormState(R.string.invalid_username, null));
        } else if (!isPasswordValid(password)) {
            loginFormState.setValue(new LoginFormState(null, R.string.invalid_password));
        } else {
            loginFormState.setValue(new LoginFormState(true));
        }
    }

    // A placeholder username validation check
    private boolean isUserNameValid(String username) {
        if (username == null || username.length()<4) {
            return false;
        }
        if (username.contains("@")) {
            return Patterns.EMAIL_ADDRESS.matcher(username).matches();
        } else {
            return !username.trim().isEmpty();
        }
    }

    // A placeholder password validation check
    private boolean isPasswordValid(String password) {
        return password != null && password.trim().length() >= 6;
    }
}
